import React from 'react';
import { Button, List, Toast, WhiteSpace, WingBlank } from 'antd-mobile';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import MyIcon from '../Base/MyIcon';
import styles from './HomeMe.css';
import Cropper from 'cropperjs';
import 'cropperjs/src/css/cropper.css';
import fetch from '../../utils/fetch';
import { updateUser } from '../../services/authService';
import { version } from '../../utils/data';

const Item = List.Item;

class HomeGrid extends React.Component {

  state = {
    editImgState: false,
  }

  toPosition = (roles) => {
    if (roles.indexOf('salesman') !== -1) {
      return <span style={{ backgroundColor: 'rgb(59, 219, 59)' }} className={styles.position}>店员</span>;
    } else if (roles.indexOf('manager') !== -1) {
      return <span style={{ backgroundColor: 'rgb(130, 72, 238)' }} className={styles.position}>店长</span>;
    } else if (roles.indexOf('supervisor') !== -1) {
      return <span style={{ backgroundColor: 'rgb(239, 85, 60)' }} className={styles.position}>督导</span>;
    } else if (roles.indexOf('operator') !== -1) {
      return <span style={{ backgroundColor: 'rgb(252, 193, 35)' }} className={styles.position}>运营</span>;
    } else if (roles.indexOf('boss') !== -1) {
      return <span style={{ backgroundColor: 'rgb(241, 75, 122)' }} className={styles.position}>老板</span>;
    }
  };

  changeFile = (e) => {
    const file = URL.createObjectURL(e.target.files[0]);

    this.setState({
      editImgState: true,
    }, () => {
      this.cropperImg.src = file;
      this.cropper = new Cropper(this.cropperImg, {
        viewMode: 1,
        aspectRatio: 1 / 1,
      });
    });
  }

  finishEdit = () => {
    this.cropper.getCroppedCanvas({
      maxWidth: 500,
      maxHeight: 500,
    }).toBlob((blob) => {
      const formData = new FormData();
      formData.append('file', blob, 'avatar.jpg');

      fetch('/wx/uploadFile', {
        method: 'post',
        body: formData,
      },
      ).then(({ data }) => {
        if (data.fileUrl) {
          updateUser(this.props.currentUser._id, {
            avatar: data.fileUrl,
          }).then(({ data }) => {
            if (data) {
              Toast.success('修改成功');
              this.props.dispatch({ type: 'auth/updateAvatar', payload: { avatar: data.profile.avatar } });
              this.cancelEdit();
            }
          });
        }
      }).catch((err) => {
        Toast.fail('出现错误，请重试', 1);
      });
    });
  }

  cancelEdit = () => {
    this.cropper.destroy();
    this.setState({
      editImgState: false,
    });
  }

  render() {
    const { dispatch } = this.props;
    const { profile: { avatar }, saleManName, phone, roles, shopName, branchName, username } = this.props.currentUser;
    const { editImgState } = this.state;

    if (editImgState) {
      return (
        <div>
          <div>
            <img
              ref={(el) => {
                this.cropperImg = el;
              }} src={require('../../assets/loading.jpg')} style={{ maxWidth: '100%', maxHeight: '80vh' }}
            />
          </div>
          <WingBlank style={{ marginTop: '0.2rem', position: 'relative' }}>
            <Button onClick={this.cancelEdit} inline>取消</Button>
            <Button onClick={this.finishEdit} inline style={{ float: 'right' }}>确定</Button>
          </WingBlank>
        </div>
      );
    }

    return (
      <div>
        <div className={styles.avatar_wrap}>
          <img
            onClick={() => {
              this.input.click();
            }} src={avatar || require("../../assets/avatar.png")} alt="" className={styles.avatar}
          />
          <input
            ref={(el) => {
              this.input = el;
            }} onChange={this.changeFile} type="file" accept="image/*" name="" id="" style={{ display: 'none' }}
          />
          <div className={styles.avatar_name}>
            <span>{saleManName || username || ''}</span>
            {this.toPosition(roles)}
          </div>
          <div className={styles.shopName}>
            {shopName}-{branchName}
          </div>
        </div>
        <List>
          <Item
            thumb={<MyIcon type="password1" style={{ color: '#4fa1c5' }} />}
            arrow="horizontal" onClick={() => {
              dispatch(routerRedux.push({
                pathname: '/resetPassword',
              }));
            }}
          >
            修改密码
          </Item>
          <Item
            thumb={<MyIcon type="feedback" style={{ color: '#4fa1c5' }} />}
            arrow="horizontal" onClick={() => {
              dispatch(routerRedux.push({
                pathname: '/help',
              }));
            }}
          >
            帮助与反馈
          </Item>
          <Item
            thumb={<MyIcon type="version" style={{ color: '#4fa1c5' }} />}
            extra={version.data[0].name}
            arrow="horizontal" onClick={() => {
              dispatch(routerRedux.push({
                pathname: '/versionRecord',
              }));
            }}
          >
            版本与更新
            {
              !version.isClick()&&
              <img src={require('../../assets/badge.png')} style={{width: '8px', height:'8px', verticalAlign: 'top' }} alt=""/>
            }
          </Item>
        </List>
        <WhiteSpace size="lg" />
        <Button
          style={{
            marginLeft: '0.16rem',
            marginRight: '0.16rem',
            color: 'rgb(229, 13, 13)',
            borderColor: 'rgba(229, 13, 13, 0.5)',
          }}
          onClick={() => {
            dispatch({ type: 'auth/logout' });
          }}
        >退出当前账号</Button>
      </div>
    );
  }

}

export default connect(({ auth: { currentUser } }) => {
  return { currentUser };
})(HomeGrid);
